import router from '@/router'
import progress from 'nprogress'
import useUserStore from '@/store/modules/user.ts'
import pinia from '@/store/index.ts'
// 引入nprogress.css
import 'nprogress/nprogress.css'
import setting from '@/setting.ts'
import { ElMessage } from 'element-plus'
//全局进度条的配置
progress.configure({
    easing: 'ease', // 动画方式
    showSpinner: false, // 是否显示加载ico
    parent: 'body', //指定进度条的父容器
})
const userStore = useUserStore(pinia)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
router.beforeEach(async (to, from, next) => {
    progress.start()
    //获取token,去判断用户登录、还是未登录
    const token = userStore.token
    //获取用户名字
    const nickName = userStore.nickName
    if (token) {
        if (to.path === '/login') {
            next({ path: '/' })
        } else {
            if (!nickName) {
                try {
                    //去拿用户信息
                    await userStore.userInfo()
                    //万一:刷新的时候是异步路由,有可能获取到用户信息、异步路由还没有加载完毕,出现空白的效果
                    next({ ...to, replace: true })
                    // 拿不到用户信息，就是token过期
                } catch (error) {
                    //token过期:获取不到用户信息了
                    //用户手动修改本地存储token
                    //退出登录->用户相关的数据清空
                    // userStore.resetToken()
                    // 一定要先清空token
                    userStore.resetToken()
                    ElMessage({
                        type: 'error',
                        message: error as string,
                    })
                    next({ path: '/login', query: { redirect: to.path } })
                }
            } else {
                next()
            }
        }
    } else {
        if (to.path === '/login') {
            next()
        } else {
            ElMessage({
                type: 'error',
                message: 'token失效，请重新登录',
            })
            next({ path: '/login', query: { redirect: to.path } })
        }
    }
})

router.afterEach((to) => {
    progress.done()
    document.title = to.meta.title
        ? `${setting.title} | ${to.meta.title}`
        : setting.title
})
